<script setup lang="ts">
import { onBeforeMount, onMounted, onUnmounted, ref, watch } from "vue";
import { useDebounceFn, useThrottleFn } from "@vueuse/core";
import setIntroduction from "@/utils/setIconfont";
import { ipcRenderer, type IpcRendererEvent } from "electron";
import { useRoute } from "vue-router";
import { emitter } from "@/utils/mitt";
import {
  getPlayDefaultMessage,
  initSynthEvent,
  playMsgByTts,
} from "@/demos/node";
import zhCnLocale from "element-plus/es/locale/lang/zh-cn";

import GlobalLoading from "@/components/GlobalLoading.vue";

const route = useRoute();

onBeforeMount(() => {
  // 设置批量第三方 icon 图标
  setIntroduction.cssCdn();
  // 设置批量第三方 js
  setIntroduction.jsCdn();
});

/**
 * 选择完回调
 * @param event
 * @param localPath
 */
const onSelectedDirectory = (event: IpcRendererEvent, localPath: string) => {
  if (event) emitter.emit(`on-directory-${route.fullPath}`, localPath);
};

const onVisibleChange = (event: IpcRendererEvent, visible: boolean) => {
  if (event) emitter.emit(`on-visible-${route.fullPath}`, visible);
};

let moveCount = 0;
const loading = ref(false);
const clearMoveCount = useDebounceFn(() => {
  moveCount = 0;
}, 300);

const onMoveChange = useThrottleFn(() => {
  moveCount += 1;
  if (moveCount > 30 && !loading.value) {
    loading.value = true;
    const message = getPlayDefaultMessage();
    playMsgByTts(message, true).finally(() => (loading.value = false));
  }
  clearMoveCount();
}, 100);

/**
 * 主程序事件通讯
 */
const onIpcRenderer = () => {
  ipcRenderer.on("on-move-change", onMoveChange);
  ipcRenderer.on("selected-directory", onSelectedDirectory);
  ipcRenderer.on("on-visible-change", onVisibleChange);
};

/**
 * 主程序事件通讯销毁
 */
const offIpcRenderer = () => {
  ipcRenderer.removeListener("on-move-change", onMoveChange);
  ipcRenderer.removeListener("selected-directory", onSelectedDirectory);
  ipcRenderer.removeListener("on-visible-change", onVisibleChange);
};

onMounted(() => {
  onIpcRenderer();
  initSynthEvent();
});

onUnmounted(() => {
  offIpcRenderer();
});
</script>
<template>
  <el-config-provider size="small" :locale="zhCnLocale">
    <router-view />
    <GlobalLoading />
  </el-config-provider>
</template>

<style lang="scss">
@import url("@/styles/index.scss");
</style>
